<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="订单号">
              <el-input v-model="query.orderId" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报名日期">
              <el-date-picker v-model="query.createTime" type="daterange" :picker-options="pickerOptions" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" clearable :editable="false"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="师训标题">
              <el-input v-model="query.trainTitle" clearable />
            </el-form-item>
          </el-col>

          <template v-if="showAll">
            <el-col :span="6">
              <el-form-item label="报名校区">
                <el-select v-model="query.campusName" placeholder="请选择校区" clearable filterable :loading="campusLoading" @focus="loadCampusOptions" :style="{ width: '100%' }">
                  <el-option v-for="item in campusOptions" :key="item.id" :label="item.fullName + '(' + item.enCode + ')'" :value="item.fullName" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="老师姓名">
                <el-input v-model="query.teacherName" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="参训状态">
                <el-select v-model="query.status" placeholder="请选择" clearable :style="{ width: '100%' }" multiple>
                  <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.fullName" :value="item.enCode"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()" native-type="submit">{{ $t('common.search') }}</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">{{ $t('common.reset') }}</el-button>
              <el-button type="text" icon="el-icon-arrow-down" @click="showAll = true" v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll = false" v-else>收起</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div class="cu-common-head-left">
            <el-button v-has="'btn_audit'" type="info" @click="addOrUpdateSupplement">结业补录</el-button>
            <el-button v-has="'btn_complete'" type="success" @click="completeHandle()">批量结业</el-button>
            <el-button v-has="'btn_delay'" type="warning" @click="delayHandle()">批量延期</el-button>
            <el-button v-has="'btn_import'" type="primary" @click="importGroup()" icon="el-icon-upload2">批量导入分组</el-button>
            <el-button v-has="'btn_download'" type="text" icon="el-icon-download" @click="exportData()">导出</el-button>
          </div>
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <custom-table v-loading="listLoading" :data="list" :hasC="true" @selection-change="handleSelectionChange" :border="true">
          <el-table-column v-if="custom.hasP('orderId')" label="订单号" prop="orderId" align="center" show-overflow-tooltip width="150"></el-table-column>
          <el-table-column v-if="custom.hasP('trainTitle')" label="师训名称" prop="trainTitle" align="left" show-overflow-tooltip width="160"></el-table-column>
          <!-- <el-table-column v-if="custom.hasP('campusEncode')" label="校区编码" prop="campusEncode" align="center">
          </el-table-column> -->
          <el-table-column v-if="custom.hasP('campusName')" label="校区简称" prop="shortName" align="left" width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.shortName + '(' + scope.row.enCode + ')' }}
            </template>
          </el-table-column>
          <el-table-column v-if="custom.hasP('area')" label="行政区域" prop="area" width="130" align="left" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.province }}-{{ scope.row.city }}
            </template>
          </el-table-column>
          <el-table-column v-if="custom.hasP('campusEndDate')" label="服务截止日期" prop="serviceEndDate" align="center" :formatter="custom.tableDateFormat" width="100"></el-table-column>
          <el-table-column label="校区状态" prop="campusStatus" align="center" width="80">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.campusStatus == 'preparation'" key="筹备" type="" effect="dark">
                筹备
              </el-tag>
              <el-tag v-if="scope.row.campusStatus == 'normal'" key="正常" type="success" effect="dark">
                正常
              </el-tag>
              <el-tag v-if="scope.row.campusStatus == 'expires'" key="到期" type="info" effect="dark">
                待续费
              </el-tag>
              <el-tag v-else-if="scope.row.campusStatus == 'suspended'" key="暂停" type="warning" effect="dark">
                暂停
              </el-tag>
              <el-tag v-else-if="scope.row.campusStatus == 'close'" key="闭校" type="danger" effect="dark">
                闭校
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="custom.hasP('teacherName')" label="参训人" prop="teacherName" align="left" width="80px"></el-table-column>

          <el-table-column v-if="custom.hasP('position')" label="职位" prop="position" width="70px"></el-table-column>
          <el-table-column v-if="custom.hasP('gender')" label="性别" prop="gender" align="center" width="60px"></el-table-column>
          <el-table-column v-if="custom.hasP('payTime')" prop="payTime" label="付款时间" :formatter="custom.tableDateTimeFormat" align="center" width="120px" />
          <el-table-column v-if="custom.hasP('statusText')" label="参训状态" prop="statusText" align="center" width="80"></el-table-column>
          <el-table-column v-if="custom.hasP('signTime')" label="签到时间" prop="signTime" :formatter="custom.tableDateTimeFormat" align="center" width="120"></el-table-column>
          <el-table-column label="所在组别" v-if="custom.hasP('group')" prop="group" align="left" width="120px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.group" placeholder="请输入组别" size="mini" @blur="onSetGroup(scope.row.id, scope.row.group)"></el-input>
            </template>
          </el-table-column>
          <el-table-column v-if="custom.hasP('mobile')" prop="mobile" label="联系方式" align="center" width="100" />
          <el-table-column v-if="custom.hasP('idCard')" prop="idCard" label="身份证号码" align="center" width="150" />
          <el-table-column v-if="custom.hasP('idCard')" prop="description" label="备注说明" align="center" width="150" />
          <el-table-column v-if="custom.hasP('photo')" prop="photo" label="证件照" align="center" width="80">
            <template slot-scope="scope">
              <el-image v-if="scope.row.photo != 'standard.png' && scope.row.photo != null" style="width: 10px; height: 30px;" :src="scope.row.photo" :preview-src-list="[scope.row.photo]" :z-index="2100"></el-image>
            </template>
          </el-table-column>
          <el-table-column v-if="custom.hasP('certificateNo')" prop="certificateNo" label="证书编号" align="center" width="140px" />
          <el-table-column v-if="custom.hasP('completeDate')" prop="completeDate" label="结业日期" :formatter="custom.tableDateFormat" align="center" width="100px" />
          <el-table-column label="操作" fixed="right" min-width="120" align="center">
            <template slot-scope="scope">
              <table-opts @edit="addOrUpdateHandle(scope.row.id)" @del="handleDel(scope.row.id)">
                <!-- <el-button type="text" :disabled="scope.row.status == 'Refunded'" @click="handleRefund(scope.row.id)" v-has="'btn_refund'">退款</el-button> -->
                <el-dropdown v-has="'btn_change'">
                  <span class="el-dropdown-link">
                    <el-button type="text" size="mini">
                      更换
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-has="'btn_train'" @click.native="handleTrainChange(scope.row)">
                      师训
                    </el-dropdown-item>
                    <el-dropdown-item v-has="'btn_teacher'" @click.native="handleTeacherChange(scope.row)">
                      校区/老师
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </table-opts>
            </template>
          </el-table-column>
        </custom-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <custom-form v-if="formVisible" ref="CustomForm" @refresh="refresh" />
    <train-form v-if="trainFormVisible" ref="TrainForm" @refresh="refresh" />
    <teacher-form v-if="teacherFormVisible" ref="TeacherForm" @refresh="refresh" />
    <export-box v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <import-box v-if="importBoxVisible" ref="ImportBox" @import="handleImport" />
    <el-dialog title="批量审批中，请耐心等待！" :visible.sync="showProgress" width="30%">
      <el-progress :text-inside="true" :stroke-width="26" :percentage="process"></el-progress>
    </el-dialog>

    <supplement-form v-if="supplementFormVisible" ref="SupplementForm" @refresh="refresh" />
  </div>
</template>
<script>
import request from '@/utils/request'
import { batchSetGroup } from '@/api/campus/trainOrderItem'
import { getCampusSelector } from '@/api/campus/campus'
import CustomForm from './Form'
import TrainForm from './TrainForm'
import TeacherForm from './TeacherForm'
import ExportBox from './ExportBox'
import ImportBox from './ImportBox'
import custom from '@/utils/custom'
import SupplementForm from './Form/index.vue'
export default {
  name: 'train_graduation',
  components: { CustomForm, TrainForm, TeacherForm, ExportBox, ImportBox, SupplementForm },
  data() {
    return {
      showAll: false,
      query: {
        orderId: undefined,
        createTime: undefined,
        trainTitle: undefined,
        campusName: undefined,
        teacherName: undefined,
        mobile: undefined,
        status: undefined
      },
      campusOptions: [],
      campusLoading: false,
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 50,
        sort: 'desc',
        sidx: 'payTime'
      },
      formVisible: false,
      supplementFormVisible: false,
      trainFormVisible: false,
      teacherFormVisible: false,
      exportBoxVisible: false,
      importBoxVisible: false,
      columnList: [{ prop: 'orderId', label: '序号' }, { prop: 'trainTitle', label: '师训名称' }, { prop: 'enCode', label: '校区编号' }, { prop: 'province', label: '省份' }, { prop: 'city', label: '城市' }, { prop: 'shortName', label: '校区简称' }, { prop: 'teacherName', label: '参训人' }, { prop: 'position', label: '职位' }, { prop: 'gender', label: '性别' }, { prop: 'mobile', label: '电话' }, { prop: 'idCard', label: '身份证' }, { prop: 'createTime', label: '报名时间' }, { prop: 'group', label: '组别' }, { prop: 'statusText', label: '参训状态' }, { prop: 'campusStatusText', label: '校区状态' }, { prop: 'levelText', label: '校区阶段' }, { prop: 'payTime', label: '付款时间' }, { prop: 'payAmount', label: '付款金额' }, { prop: 'refundCode', label: '退款单号' }, { prop: 'refundAmount', label: '退款金额' }, { prop: 'signTime', label: '签到时间' }, { prop: 'id', label: '数据标识（导入需要）' }],
      genderOptions: [],
      statusOptions: [],
      payStatusOptions: [],
      campusStatusOptions: [],
      showProgress: false,
      process: 0,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const today = new Date()
              let daterange = custom.getLastWeekDays(today, 1)
              picker.$emit('pick', [new Date(daterange.starttime), today])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const today = new Date()
              let daterange = custom.getLastMonthDays(today, 1)
              picker.$emit('pick', [new Date(daterange.starttime), today])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const today = new Date()
              let daterange = custom.getLastMonthDays(today, 3)
              picker.$emit('pick', [new Date(daterange.starttime), today])
            }
          }
        ]
      }
    }
  },
  computed: {},
  created() {
    this.defaultDate()
    this.initData()
    this.loadCampusOptions()
    this.$store.dispatch('base/getDictionaryData', { sort: 'sex' }).then(res => {
      this.genderOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'SignStatus' }).then(res => {
      this.statusOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'PayStatus' }).then(res => {
      this.payStatusOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'CampusStatus' }).then(res => {
      this.campusStatusOptions = res
    })
  },
  methods: {
    async loadCampusOptions() {
      try {
        this.campusLoading = true
        const params = { fields: 'id,fullName' }
        const res = await getCampusSelector(params)
        this.campusOptions = Array.isArray(res.data) ? res.data : []
      } catch (error) {
        console.error('加载校区数据失败:', error)
        this.$message.error('加载校区数据失败')
        this.campusOptions = []
      } finally {
        this.campusLoading = false
      }
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: `/api/train/sign`,
        method: 'GET',
        data: query
      }).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    onSetGroup(id, value) {
      this.$confirm('此操作将修改学员所在组别信息, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/train/sign/${id}/setgroup/${value}`,
            method: 'post',
            data: {
              id,
              value
            }
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                // this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/train/sign${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },
    addOrUpdateSupplement() {
      this.supplementFormVisible = true
      this.$nextTick(() => {
        this.$refs.SupplementForm.init()
      })
    },

    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 50,
        sort: 'desc',
        sidx: 'payTime'
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.query.payStatus = 'Yes'
      this.listQuery = {
        currentPage: 1,
        pageSize: 50,
        sort: 'desc',
        sidx: 'payTime'
      }
      this.defaultDate()
      this.initData()
    },
    defaultDate() {
      //获取新的时间(2019.4.12）
      let today = new Date()
      let daterange = custom.getLastMonthDays(today, 1)
      this.query.createTime = [daterange.starttime, custom.dateFormat(today, 'YYYY-MM-DD')] //将值设置给插件绑定的数据
    },
    handleSelectionChange(val) {
      this.multipleSelection = this.reduceSame(val)
    },
    // 数组对象去重
    reduceSame(arr) {
      let obj = {}
      return arr.reduce(function(prev, item) {
        obj[item.id] ? '' : (obj[item.id] = 1 && prev.push(item))
        return prev
      }, [])
    },
    // 结业
    completeHandle() {
      if (this.multipleSelection.length > 0) {
        this.$confirm('请确认需要的操作', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '结业',
          cancelButtonText: '肄业',
          type: 'warning'
        })
          .then(async action => {
            for (var i = 0; i < this.multipleSelection.length; i++) {
              this.showProgress = true
              let item = this.multipleSelection[i]
              await request({
                url: `/api/train/sign/stauts/${item.id}/complete`,
                method: 'POST'
              })
                .then(res => {
                  this.process = parseInt(((i + 1) / this.multipleSelection.length) * 100)
                })
                .catch(err => {
                  console.log(err)
                })
            }
            this.$message({
              type: 'success',
              message: '批量通过完成',
              duration: 1000,
              onClose: () => {
                this.$emit('close', true)
              }
            })
            this.showProgress = false
            this.process = 0
            this.search()
          })
          .catch(async action => {
            if (action === 'close') {
              return false
            } else if (action === 'cancel') {
              for (var i = 0; i < this.multipleSelection.length; i++) {
                this.showProgress = true
                let item = this.multipleSelection[i]
                console.log(item)
                await request({
                  url: `/api/train/sign/stauts/${item.id}/undergraduate`,
                  method: 'POST'
                }).then(res => {
                  this.process = parseInt(((i + 1) / this.multipleSelection.length) * 100)
                })
              }
              this.$message({
                type: 'success',
                message: '批量操作完成',
                duration: 1000,
                onClose: () => {
                  this.$emit('close', true)
                }
              })
              this.showProgress = false
              this.process = 0
              this.search()
            }
          })
      } else {
        this.$message({
          message: '请选择需要结业的数据！',
          type: 'warning'
        })
      }
    },
    delayHandle() {
      if (this.multipleSelection.length > 0) {
        this.$confirm('请确认需要的操作', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          for (var i = 0; i < this.multipleSelection.length; i++) {
            this.showProgress = true
            let item = this.multipleSelection[i]
            await request({
              url: `/api/train/sign/stauts/${item.id}/delay`,
              method: 'POST'
            }).then(res => {
              this.process = parseInt(((i + 1) / this.multipleSelection.length) * 100)
            })
          }
          this.$message({
            type: 'success',
            message: '批量通过完成',
            duration: 1000,
            onClose: () => {
              this.$emit('close', true)
            }
          })
          this.showProgress = false
          this.process = 0
          this.search()
        })
      } else {
        this.$message({
          message: '请选择需要操作的数据！',
          type: 'warning'
        })
      }
    },
    handleRefund(id) {
      this.$confirm('请确认需要的操作', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '通过',
        cancelButtonText: '拒绝',
        type: 'warning'
      })
        .then(async action => {
          this.listLoading = true
          request({
            url: `/api/train/sign/refund/${id}`,
            method: 'POST'
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.listLoading = false
                this.search()
              }
            })
          })
          this.search()
        })
        .catch(async ({ action }) => {})
    },

    handleTrainChange(row) {
      if (row.trainId == null) {
        this.$message({
          message: '请选择更换需要参训的师训！',
          type: 'warning'
        })
      }
      this.trainFormVisible = true
      this.$nextTick(() => {
        this.$refs.TrainForm.init(row.id)
      })
    },
    handleTeacherChange(row) {
      this.teacherFormVisible = true
      this.$nextTick(() => {
        this.$refs.TeacherForm.init(row.id, row)
      })
    },
    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList)
      })
    },
    download(data) {
      this.$message({
        message: '文件下载链接稍后推送到站内信，请在右上角铃铛图标处查收！',
        type: 'success',
        showClose: true,
        duration: 0
      })
      this.$refs.ExportBox.visible = false
      this.exportBoxVisible = false
      let _query = { ...data, ...this.listQuery, ...this.query }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      query['ids'] = this.multipleSelection
        .map(i => {
          return i.id
        })
        .join(',')
      request({
        url: `/api/train/sign/Actions/Export`,
        method: 'GET',
        data: query
      }).then(res => {})
    },
    // 显示导入弹窗
    importGroup() {
      this.importBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ImportBox.init()
      })
    },
    // 处理导入数据
    async handleImport(importData) {
      try {
        const { data } = importData

        this.$message({
          message: '正在查找匹配的师训订单项...',
          type: 'info',
          duration: 2000
        })

        // 直接将解析后的数据发送到后端处理，不进行前端匹配
        if (data.length === 0) {
          this.$message({
            message: '没有有效的数据可以导入',
            type: 'warning'
          })
          return
        }

        // 调用批量设置分组API，直接传递原始数据到后端处理
        const result = await batchSetGroup(data)

        if (result.data && result.data.success) {
          this.$message({
            message: result.data.message || `批量设置分组成功，共处理 ${data.length} 条数据`,
            type: 'success',
            duration: 3000
          })

          // 刷新列表
          this.initData()
        } else {
          this.$message({
            message: (result.data && result.data.message) || '批量设置分组失败',
            type: 'error'
          })
        }
      } catch (error) {
        console.error('批量设置分组失败:', error)
        this.$message({
          message: '批量设置分组过程中发生错误，请重试',
          type: 'error'
        })
      } finally {
        this.$refs.ImportBox.btnLoading = false
        this.$refs.ImportBox.visible = false
        this.importBoxVisible = false
      }
    }
  }
}
</script>
